#include "unistd.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include <sys/mman.h>
#include <sys/types.h>
#include <ctype.h>
#include <sys/stat.h>
#include <fcntl.h>

#define SDRAM_PHY_Position 0xc0000000
#define GPIO_EXPORT "/sys/class/gpio/export"
#define GPIO_DIRECTION_PREFIX "/sys/class/gpio/gpio%d/direction"
#define GPIO_VALUE_PREFIX "/sys/class/gpio/gpio%d/value"
#define GPIO1_NUM 34
#define GPIO2_NUM 237

int get_gpio(int gpio_num)
{
	FILE *p = NULL;
	char str[256];
	char buffer[2];
	int val = -1;
    p = fopen("/sys/class/gpio/export", "w");
    if (p == NULL) {
        return -1;
    }
    fprintf(p, "%d", gpio_num);
    fclose(p);
    sprintf(str, "/sys/class/gpio/gpio%d/direction", gpio_num);
    p = fopen(str, "w");
    if (p == NULL) {
        return -1;
    }
    fprintf(p, "in");
    fclose(p);

	sprintf(str, "/sys/class/gpio/gpio%d/value", gpio_num);
	p = fopen(str, "r");
	if (p == NULL) {
		return -1;
	}
	
	if (fread(buffer, 1, 1, p) == 1) {
		buffer[1] = '\0';
		val = buffer[0] - '0';
	}

	return val;
}

void set_gpio(int gpio_num, int gpio_val)
{
	FILE *p = NULL;
	char str[256];
    p = fopen("/sys/class/gpio/export", "w");
    if (p == NULL) {
        return;
    }
    fprintf(p, "%d", gpio_num);
    fclose(p);
    sprintf(str, "/sys/class/gpio/gpio%d/direction", gpio_num);
    p = fopen(str, "w");
    if (p == NULL) {
        return;
    }
    fprintf(p, "out");
    fclose(p);

	sprintf(str, "/sys/class/gpio/gpio%d/value", gpio_num);
	p = fopen(str, "w");
	if (p == NULL) {
		return;
	}
	fprintf(p, "%d", gpio_val);
	fclose(p);
}


